// AI Configuration Service
// This service manages AI API tokens and configuration settings

const AI_CONFIG_KEY = 'aiConfig';
const DEFAULT_CONFIG = {
  apiToken: '',
  provider: 'openai-compatible', // openai, anthropic, openai-compatible, etc.
  model: 'glm-4.6', // default model for video generation
  endpoint: 'https://api.kilocode.ai/v1', // Default endpoint for Kilo Code
  maxTokens: 4000,
  temperature: 0.7
};

/**
 * Get AI configuration from localStorage
 * @returns {Object} AI configuration object
 */
export const getAIConfig = () => {
  try {
    const config = localStorage.getItem(AI_CONFIG_KEY);
    return config ? { ...DEFAULT_CONFIG, ...JSON.parse(config) } : DEFAULT_CONFIG;
  } catch (error) {
    console.error('Error getting AI config:', error);
    return DEFAULT_CONFIG;
  }
};

/**
 * Save AI configuration to localStorage
 * @param {Object} config - AI configuration object
 * @returns {boolean} Success status
 */
export const saveAIConfig = (config) => {
  try {
    const currentConfig = getAIConfig();
    const newConfig = { ...currentConfig, ...config };
    localStorage.setItem(AI_CONFIG_KEY, JSON.stringify(newConfig));
    return true;
  } catch (error) {
    console.error('Error saving AI config:', error);
    return false;
  }
};

/**
 * Check if AI API token is configured
 * @returns {boolean} Token status
 */
export const isTokenConfigured = () => {
  const config = getAIConfig();
  return !!config.apiToken;
};

/**
 * Get API headers for AI requests
 * @returns {Object} Headers object
 */
export const getAPIHeaders = () => {
  const config = getAIConfig();
  return {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${config.apiToken}`
  };
};

/**
 * Validate API token format (basic validation)
 * @param {string} token - API token to validate
 * @returns {boolean} Validation result
 */
export const validateToken = (token) => {
  if (!token || typeof token !== 'string') {
    return false;
  }
  
  // Basic validation for OpenAI tokens (starts with 'sk-')
  if (token.startsWith('sk-') && token.length > 20) {
    return true;
  }
  
  // For Kilo Code tokens (starts with 'kc-')
  if (token.startsWith('kc-') && token.length > 20) {
    return true;
  }
  
  // For other providers, just check if it's a reasonable length
  return token.length > 10;
};

/**
 * Reset AI configuration to defaults
 * @returns {boolean} Success status
 */
export const resetAIConfig = () => {
  try {
    localStorage.setItem(AI_CONFIG_KEY, JSON.stringify(DEFAULT_CONFIG));
    return true;
  } catch (error) {
    console.error('Error resetting AI config:', error);
    return false;
  }
};

/**
 * Get available AI providers
 * @returns {Array} Array of provider objects
 */
export const getAvailableProviders = () => {
  return [
    {
      id: 'openai',
      name: 'OpenAI',
      models: [
        { id: 'gpt-4-vision-preview', name: 'GPT-4 Vision Preview' },
        { id: 'gpt-4', name: 'GPT-4' },
        { id: 'gpt-3.5-turbo', name: 'GPT-3.5 Turbo' }
      ],
      endpoint: 'https://api.openai.com/v1'
    },
    {
      id: 'anthropic',
      name: 'Anthropic',
      models: [
        { id: 'claude-3-opus-20240229', name: 'Claude 3 Opus' },
        { id: 'claude-3-sonnet-20240229', name: 'Claude 3 Sonnet' },
        { id: 'claude-3-haiku-20240307', name: 'Claude 3 Haiku' }
      ],
      endpoint: 'https://api.anthropic.com'
    },
    {
      id: 'openai-compatible',
      name: 'Kilo Code',
      models: [
        { id: 'glm-4.6', name: 'GLM-4.6' },
        { id: 'glm-4', name: 'GLM-4' },
        { id: 'glm-3-turbo', name: 'GLM-3 Turbo' }
      ],
      endpoint: 'https://api.kilocode.ai/v1'
    }
  ];
};

/**
 * Get models for a specific provider
 * @param {string} providerId - Provider ID
 * @returns {Array} Array of model objects
 */
export const getProviderModels = (providerId) => {
  const providers = getAvailableProviders();
  const provider = providers.find(p => p.id === providerId);
  return provider ? provider.models : [];
};